let app = getApp();
let location = require("../../../mybehaviors/location/location");
Component({
  /**
   * 组件的属性列表
   */
  behaviors: [location],
  properties: {
    datas: {
      type: null
    },
    fixedTop: {
      type: Boolean,
      value: false
    },
    bottomShowBol: {
      type: null,
    },
    showDropdownMenu: {
      type:false
    },
    bottomShowBolIndex: {
      type: null,
    },
    index: {
      type: null,
    },
    btnFlag: {
      type: null
    },
    pageScrollTopV: {
      type: null,
      value: 0
    },
  },
  options: {
    addGlobalClass: true,
    styleIsolation: 'shared',
  },

  /**
   * 组件的初始数据
   */
  data: {
    tabIndex: 0,
    navbarInitTop: 0, //距离顶部的距离
    tabs: [],
    arrIndex:1, //组件加载下一页
    language: '',
    perPage:15, //每页多少条数据
    couponGoodsList:[], //商品信息
    list:[], //商品加载
    isLoadMore: true,
    allLoaded: false, //全部数据加载完成
    //分类查询信息
    query: {
      basic_info: 1,
      page:1,
      longitude: '',
      latitude: '',
      order_by: 'distance',
      search: {
        is_recommand: 0,
        province_id: 0,
        city_id: 0,
        district_id: 0,
        street_id: 0,
        is_free: 0, //是否霸王餐
        is_group: 0, //是否拼团商品
        is_new: 0, //是否新品
        category_ids: [], //装修接口返回的分类ID，一维数组
        category_id: 0, //分类ID
      }
    },
    love:'',
    point:'',
    totalPage:0,
    //选择的地址信息
    cityId: [],
    provinceData: [],
    cityData: [],
    districtData: [],
    addressData: [{
      text: '全国',
      value: 0
    }],
    distance: [{
        text: '距离优先',
        value: 'distance'
      },
      {
        text: '人气优先',
        value: 'visit_count'
      },
      {
        text: '上新优先',
        value: 'start_time'
      },
    ],
    //全部分类信息
    lastClassId:0, //分类classId
    nextClassId:0, //分类nextClassId
    firstId: 0,  //获取分类的全部推荐二级
    secondId: 0,
    categoryList: [], //一级分类
    secondArr: [], //二级分类
    threeArr: [],
    categoryIndex: 0, //一级分类索引
    secondIndex: 0,
    threeIndex: 0,
    styleTwoIndex: null,
    styleThreeIndex: null,
    //下拉菜单筛选的值
    cityValue: 0,
    classifyValue: '全部分类',

    tagBgColor: '#ffffff',
    container: null,//指定dropMenu组件的容器
    stickyRefresh: false//切换时隐藏下拉框
  },
  observers: {
    datas: function (data) {
      if (this.data.totalPage <= this.data.page) {
        this.setData({
          isLoadMore: false,
          allLoaded: true,
        });
      }
      
    },
    bottomShowBol: function (flag) {
      if (flag && this.data.bottomShowBolIndex == this.data.index && this.data.isLoadMore) {
        this.getMoreData();
      } else if (this.data.page >= this.data.totalPage) {
        if (this.data.couponGoodsList.slice(this.data.per_page * this.data.arrIndex).length > 0) {
          this.setData({
            list: this.data.list.concat(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1))),
            arrIndex: this.data.arrIndex + 1
          });
        }
      }
    },
  },
  lifetimes: {
    created() {
      // 粘性顶部  //获取节点距离顶部的距离
      // 获取SelectorQuery 对象实例

    },
    attached: function () {

      let language = wx.getStorageSync("langIndex");
      this.setData({
        language: language.en,
      });
     
      // let newDecorate = wx.getStorageSync("new_decorate"); //获取缓存的装修数据
      let tabsTitle = ['diy_title_1', 'diy_title_2', 'diy_title_3', 'diy_title_4', 'diy_title_5'];
      let tabs = this.data.tabs;
      // let finishDatas = newDecorate.item.datas;
      let decoration = [];
      
      // if(newDecorate) { //为了解决从缓存读取装修数据
      //   decoration = finishDatas.filter((item) => {
      //     return item.component_key === 'U_couponStore'
      //   })
      // }
      let datas = this.data.datas;
      
      for (let i in tabsTitle) {
        tabs.push({
          name: datas[tabsTitle[i]],
          status: Number(i) + 1   //对应后端传显示的tab数组
        })
      }
      let tabsList = tabs.filter(item=>datas['tab_list'].some(ele=>ele === String(item.status))); //筛选出显示的tab数组
      this.setData({
        tabs: tabsList,
        tagBgColor: datas.tab_bg_color
      });
      this.isTabActions(this.data.tabs[0].status);
      this.goodsCategoryList();
      this.setData({
        container: () => this.createSelectorQuery().select('#container'),//下拉框指定容器
      });
    },
  },
  pageLifetimes: {
    show: function () {
      
      // 页面被展示
    },
    hide: function () {
      // 页面被隐藏
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },

  ready(){
    //定位信息
    try {
      this._getLocation((mapdata, e) => { //获取定位的城市，拿到定位的信息
        let addressData = [];
        addressData.push({
          text: mapdata.ad_info.city,
          value: mapdata.ad_info.adcode
        })
        this.setData({
          'query.longitude': e.lng,
          'query.latitude': e.lat,
          addressData,
          cityValue: Number(mapdata.ad_info.adcode)
        });
        this._initAddressInfo();
      });
    
  } catch (e) {
    console.log(e);
  }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    goodsCategoryList() {
      let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.category.goodsCategoryList");
      let json = {};
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.list;
          if (res.result == 1) {
            let secondArr = [];
            let threeArr = [];
            if (list[this.data.categoryIndex].has_many_children && list[this.data.categoryIndex].has_many_children.length > 0) {  //查询下面数组赋值给2级菜单显示
              secondArr = list[this.data.categoryIndex].has_many_children;
            }
            if (list[this.data.categoryIndex].has_many_children && list[this.data.categoryIndex].has_many_children.length > 0) { //查询下面数组赋值给3级菜单显示
              threeArr = secondArr[this.data.secondIndex].has_many_children
            }
            if(this.data.firstId === 0) {
              this.setData({
                firstId: list[0].id
              })
            }
            this.setData({
              categoryList: list,
              secondArr,
              threeArr,
              catLevel:res.data.cat_level
            })
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    orderCouponList() {
      let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.goods.index");
      let json = this.data.query;
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.setData({
              couponGoodsList: list,
              totalPage: res.data.last_page,
              love: res.basic_info?.love,
              point: res.basic_info?.point
            })
            
          } else {
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
          return list
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    categoryAllOn() {
      this.setData({
        categoryIndex: -1,
        lastClassId:0,
        nextClassId:0,
        secondId:0,
        classifyValue: '全部推荐'
      })
      this.data.query.search.category_id = 0;
      this.orderCouponList();
      this.selectComponent('#item').toggle(false);
    },
    firstAllOn() {
      this.setData({
        styleTwoIndex: -1,
        'query.search.category_id': this.data.firstId,
        classifyValue: '全部推荐'
      })
      this.orderCouponList();
      this.selectComponent('#item').toggle(false);
    },
    threeAllOn() {
      this.setData({
        styleThreeIndex: -1,
        'query.search.category_id': this.data.secondId,
        classifyValue: '全部推荐'
      })
      this.orderCouponList();
      this.selectComponent('#item').toggle(false);
    },
    categoryOn(event) {
      const handler = event.currentTarget.dataset,
        index = handler.index,
        id = handler.id,
        name = handler.name,
        children = handler.children;
      let categoryId = this.data.query.search.category_id;
      this.getAdjacentInfo(index);
      if (this.data.categoryIndex !== index) {
        this.goodsCategoryList();
      }

      if (Array.isArray(children) && children.length === 0) { //判断是否没有子级，没有子级就传一级ID并且关闭弹窗
        categoryId = id;
        this.selectComponent('#item').toggle(false);
        this.setData({
          classifyValue: name,
          'query.search.category_id': categoryId,
        });
        this.orderCouponList(); //首页商品数据
      }
      this.setData({
        categoryIndex: index,
        secondIndex: 0,
        secondId:0,
        styleTwoIndex: null,
        firstId: id
      })
      
    },
    // 当前选中类目，相邻圆角样式所需信息
    getAdjacentInfo(index) {
      if(this.data.categoryList[index -1]) {
        this.setData({
          lastClassId: this.data.categoryList[index -1].id,
          nextClassId: this.data.categoryList[index +1]?.id || 0
        });
      } else {
        this.setData({
          nextClassId: this.data.categoryList[index +1].id
        });
        
      }
      if(index === 0 ||index === -1) {
        this.setData({
          lastClassId: 0,
        });
      }
    },
    secondOn(event) {
      const handler = event.currentTarget.dataset,
        index = handler.index,
        id = handler.id,
        name = handler.name,
        children = handler.children;
      let categoryId = this.data.query.search.category_id;
      if (Array.isArray(children) && children.length === 0 || this.data.catLevel === '2') { //判断是否没有子级，没有子级就传二级ID并且关闭弹窗
        categoryId = id;
        this.selectComponent('#item').toggle(false);
        this.setData({
          classifyValue: name,
          'query.search.category_id': categoryId,
        });
        this.orderCouponList(); //首页商品数据
      }
      if (this.data.secondIndex !== index) { //避免重复选择一个分类重复请求
        this.goodsCategoryList();
      }
      this.setData({
        secondIndex: index,
        styleTwoIndex: index,
        secondId: id
      })
      

    },
    threeOn(event) {
      const handler = event.currentTarget.dataset,
        index = handler.index,
        name = handler.name,
        id = handler.id;
      this.setData({
        threeIndex: index,
        styleThreeIndex: index,
        classifyValue: name,
        'query.search.category_id': id
      })
      this.selectComponent('#item').toggle(false);
      this.goodsCategoryList();
      this.orderCouponList(); //首页商品数据
    },
    onTabChange(event) { //获取tab的分类
      let index = event.detail.index;
      this.onMenuClose();
      this.setData({
        stickyRefresh: true
      })
      this.isTabActions(this.data.tabs[index].status);
      this.setData({
        container: () => this.createSelectorQuery().select('#container'),//下拉框指定容器
      });
      this.orderCouponList(); //首页商品数据
      setTimeout(() => {
        this.setData({
          stickyRefresh: false
        })
      }, 1000);
    },
    isTabActions(status){ //处理多层判断
      const actions = new Map([
        [{[status]:1}, () => {
          this.setData({
            'query.search.is_recommand': 1,
            'query.search.is_free': 0,
            'query.search.is_group': 0,
            'query.search.is_new': 0,
            'query.search.category_ids': [],
          })
        }],
        [{[status]:2}, () => {
          // let newDecorate = wx.getStorageSync("new_decorate"); //获取缓存的装修数据
          // let finishDatas = newDecorate.item.datas;
          // let decoration = [];
          // let datas = {};
          // if(newDecorate) { //为了解决从缓存读取装修数据
          //   decoration = finishDatas.filter((item) => {
          //     return item.component_key === 'U_couponStore'
          //   })
          // }
          let datas = this.data.datas;
          let categoryIds = datas.list.map((item) => {
            return item.id
          });
          this.setData({
            'query.search.is_recommand': 0,
            'query.search.is_free': 0,
            'query.search.is_group': 0,
            'query.search.is_new': 0,
            'query.search.category_ids': categoryIds,
          })
        }],
        [{[status]:3}, () => {
          this.setData({
            'query.search.is_recommand': 0,
            'query.search.is_free': 1,
            'query.search.is_group': 0,
            'query.search.is_new': 0,
            'query.search.category_ids': [],
          })
        }],
        [{[status]:4}, () => {
          this.setData({
            'query.search.is_recommand': 0,
            'query.search.is_free': 0,
            'query.search.is_group': 1,
            'query.search.is_new': 0,
            'query.search.category_ids': [],
          })
        }],
        [{[status]:5}, () => {
          this.setData({
            'query.search.is_recommand': 0,
            'query.search.is_free': 0,
            'query.search.is_group': 0,
            'query.search.is_new': 1,
            'query.search.category_ids': [],
          })
        }]
      ]);
      let action = [...actions].filter(  //筛选对应的map数组
        ([key,value]) => {
          return status === key[status]
      });
      action.forEach(([key,value]) => { //遍历map的数组执行里面的匿名函数
        value.call(this);
      })
    },
    onDistanceChange({ detail }) { //选择距离，新品
      this.setData({
        'query.order_by': detail,

      })
      this.orderCouponList(); //首页商品数据
      
    },
    onCityChange({ detail }) { //选择地址
      if(this.data.cityId[0].id === Number(detail)) {  //通过cityID去区别市还是区
        this.setData({
          'query.search.city_id': detail,
          'query.search.district_id':0,
        })
      } else {
        this.setData({
          'query.search.district_id': detail,
        })
      }
      this.orderCouponList(); //首页商品数据
      
    },
    onLocation() { //定位失败，获取新的定位
      this.triggerEvent("onMenuOpen",true);
      let userLocationFlag = this.checkAlbum("scope.userLocation");
      if (!userLocationFlag) {
        return app.tips("获取位置失败，请重新进入后授权");
      }
    },
    onMenuClose() {
      this.triggerEvent("onMenuClose",false);
    },
    onMenuOpen() {
      this.triggerEvent("onMenuOpen",true);
      
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = 'provinceData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          that._getCityData();
        },
        fail: function (res) {
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: 'provinceData',
                data: province
              });
              wx.setStorage({
                key: 'cityData',
                data: city
              });
              wx.setStorage({
                key: 'districtData',
                data: district
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true
          });
        }
      });
    },
    _getCityData() {
      var that = this;
      var _keyName = 'cityData';
      wx.getStorage({
        key: _keyName,
          success:  function (res) {
          let cityData = res.data;
          let provinceText = that.data.cityValue;
          let interceptionId = provinceText.toString().slice(0, 4); //截取为市的标识符
          let cityId = cityData.filter((item) => { //筛选为市的地址
            let id = item['id'].toString();
            return id.indexOf(interceptionId) !== -1;
          })
          let addressData = that.data.addressData;
          addressData[0].value = cityId[0].id;
          that.setData({
            cityValue:cityId[0].id,
            'query.search.city_id': cityId[0].id,
            cityId: cityId,
            addressData
          })
          that._getDistrictData();
          that.orderCouponList();
          // if(that.data.query.search.city_id) { //判断定位是市级加载商品列表
            
          // }
          
        }
      });
       
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.cityId;
      var that = this;
      var _keyName = 'districtData';
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data[0].id) {
              _json.push(res.data[i]);
            }
          }
          let addressData = that.data.addressData;
          _json.forEach((item) => {
            addressData.push({
              text: item.areaname,
              value: item.id
            })
          })
          that.setData({
            addressData
          });
        }
      });
    },
    async checkAlbum(scopeName) {
      let writePhotosAlbum = await this.getAuthSetting(scopeName);
      return new Promise((resolve, reject) => {
        if (!writePhotosAlbum) {
          wx.showModal({
            title: "请开启授权",
            content: "是否跳转设置页开启授权",
            success(res) {
              if (res.confirm) {
                wx.openSetting({
                  success(settingdata) {
                    if (settingdata.authSetting[scopeName]) {
                      resolve(true);
                    } else {
                      resolve(false);
                    }
                  },
                });
              } else if (res.cancel) {
                resolve(false);
              }
            },
            fail: () => {
              resolve(false);
            },
          });
        } else resolve(true);
      });
    },
    getAuthSetting(authName) {
      return new Promise((resolve, reject) => {
        wx.getSetting({
          success(res) {
            if (!res.authSetting[authName]) {
              wx.authorize({
                scope: authName,
                success() {
                  resolve(true);
                },
                fail() {
                  resolve(false);
                },
              });
            } else resolve(true);
          },
          fail() {
            resolve(false);
          },
        });
      });
    },
    // 获取更多数据
    getMoreData() {
      let that = this;
      // if (this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex).length >= this.data.perPage) {
      //   console.log(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1)));
      //   that.setData({
      //     couponGoodsList: this.data.couponGoodsList.concat(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1))),
      //     arrIndex: this.data.arrIndex + 1
      //   });
      // }
      this.setData({
        isLoadMore: false,
      });
      if (that.data.query.page >= that.data.totalPage) {
        if (this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex).length > 0) {
          that.setData({
            couponGoodsList: this.data.couponGoodsList.concat(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1))),
            arrIndex: this.data.arrIndex + 1
          });
        }
      } else {
        that.setData({
          'query.page': that.data.query.page + 1,
        });
        let urlStr = app.getNetAddresss("plugin.coupon-store.frontend.goods.index");
        let json = that.data.query;
        app._postNetWork({
          url: urlStr,
          data: json,
          success: (resdata) => {
            var res = resdata.data;
            let list = res.data.data;
            if (res.result == 1) {
                that.setData({
                  page: res.data.current_page || this.data.page,
                  couponGoodsList: this.data.couponGoodsList.concat(list),
                  perPage: res.data.per_page,
                  love: res.basic_info?.love,
                  point: res.basic_info?.point
                });
                that.setData({
                  couponGoodsList: this.data.couponGoodsList.concat(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1))),
                  arrIndex: this.data.arrIndex + 1
                });
                if (this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex).length > 0 || that.data.page < that.data.totalPage) {
                  that.setData({
                    isLoadMore: true,
                  });
                } else {
                  that.setData({
                    allLoaded: true,
                  });
                }
              } else {
                that.setData({
                  page: res.data.current_page || this.data.page,
                  couponGoodsList: this.data.couponGoodsList.concat(res.data.data),
                });
                that.setData({
                  couponGoodsList: data.concat(this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex, this.data.perPage * (this.data.arrIndex + 1))),
                  arrIndex: this.data.arrIndex + 1
                });
                if (this.data.couponGoodsList.slice(this.data.perPage * this.data.arrIndex).length > 0 || that.data.page < that.data.totalPage) {
                  // 判断是否最后一页  和 是否数据都加载完
                  that.setData({
                    isLoadMore: true,
                  });
                } else {
                  that.setData({
                    allLoaded: true,
                  });
                }
              }
              that.setData({
                page: that.data.page - 1,
                isLoadMore: false,
                allLoaded: true,
              });

          },
          fail: function (res) {
            console.log(res);
          },
        });
      }
    },
    scrollTo() {
      // 1.使用wx.createSelectorQuery()查询到需要滚动到的元素位置
      this.createSelectorQuery().select('.consumption-page').boundingClientRect(res => {
        // 到这里，我们可以从res中读到id为container的top，即离顶部的距离（px）
        // 2使用wx.pageScrollTo()将页面滚动到对应位置
        // console.log(res.top,this.data.pageScrollTopV,res.top + this.data.pageScrollTopV)
        if(res.top>0){
          wx.pageScrollTo({
            scrollTop: res.top + this.data.pageScrollTopV, // 滚动到的位置（距离顶部 px）
            duration: 0 //滚动所需时间 如果不需要滚动过渡动画，设为0（ms）
          })
        }
        
      }).exec()
    }
  },


})